package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"shop/models"
)

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}
type ShopController struct {
	beego.Controller
}

func (c *ShopController) Add() {
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	types := c.GetString("types")
	img := c.GetString("img")
	status := c.GetString("status")
	shop := models.Shop{
		Name:   name,
		Price:  price,
		Types:  types,
		Img:    img,
		Status: status,
	}
	err := models.DB.Model(&models.Shop{}).Create(&shop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: shop,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "请上传文件",
			Data: nil,
		}
		c.ServeJSON()
	}
	defer file.Close()
	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		imgUrl := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "上传成功",
			Data: imgUrl,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) Del() {
	id, _ := c.GetInt("id")
	var shop []models.Shop
	err := models.DB.Delete(&models.Shop{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: shop,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	pageData := make(map[string]interface{})
	var shop []models.Shop
	var count int64
	models.DB.Model(&models.Shop{}).Count(&count)
	offset := (page - 1) * size
	err := models.DB.Model(&models.Shop{}).Offset(offset).Limit(size).Find(&shop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		pageData["count"] = count
		pageData["shop"] = shop
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功",
			Data: shop,
		}
		c.ServeJSON()
	}
}
